// Created by WXX on 2021/3/27 11:07
#include "MyLinkedList.h"

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {

        if (k == 0 || !head) return head;

        int n = 0;
        ListNode* tail;
        for (auto p = head; p; p = p->next) {
            tail = p;
            n++;
        }
        k %= n;
        if (!k) return head;

        auto p = head;
        for (int i = 0; i < n - k - 1; i++) p = p->next;
        tail->next = head;
        head = p->next;
        p->next = NULL;

        return head;
    }
};

int main() {

    ListNode *head = MyLinkedList({1, 2, 3, 4, 5}).getHead();
    MyLinkedList().printLinkedList(Solution().rotateRight(head, 2));

    return 0;
}
